from __future__ import absolute_import
from __future__ import print_function

import json
import optparse

import websockets
from sumolib import checkBinary  # noqa
import traci  # noqa
import redis
import time
from numpy import *
import os
import sys
from common import function


# we need to import python modules from the $SUMO_HOME/tools directory
if 'SUMO_HOME' in os.environ:
    tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
    sys.path.append(tools)
else:
    sys.exit("please declare environment variable 'SUMO_HOME'")

pool = redis.ConnectionPool(host='172.18.100.27', port=32010, db=3, password=123 )
r = redis.StrictRedis(connection_pool=pool)


# 获取车辆信息
def get_veh_info(id):
    # 通过id获取x，y坐标
    x, y = traci.vehicle.getPosition(id)
    # x，y坐标转换成经纬度
    lon, lat = traci.simulation.convertGeo(x, y)
    # 获取角度
    angle = traci.vehicle.getAngle(id)
    # 获取速度
    speed = traci.vehicle.getSpeed(id)
    # 类型
    type = traci.vehicle.getTypeID(id)
    # 车辆长度
    vehLength = traci.vehicle.getLength(id)
    # 车辆宽度
    vehWidth = traci.vehicle.getWidth(id)
    # 车辆高度
    vehHeight = traci.vehicle.getHeight(id)
    # 车辆信号灯状态 (0:不开转向灯 1:右转灯 2:左转灯 8:直行减速+刹车 9:右转+刹车 10:左转+刹车)
    signal = traci.vehicle.getSignals(id)
    # 车辆颜色
    color = traci.vehicle.getColor(id)
    # 加速度
    accel = traci.vehicle.getAcceleration(id)

    arr = [lon, lat, angle, speed, vehLength, vehWidth, vehHeight, accel, signal]
    return arr


def bsm_msg_quene(message):
    msg_key = 'bsm:quene'
    r.lpush(msg_key, message)


def warning_quene(message):
    msg_key = 'warn:quene'
    r.lpush(msg_key, message)


def run():
    frame = 0
    for step in range(2000870):
        traci.simulationStep(step + 1)
        frame += 1
        # 获取路网中的车辆id
        id_list = traci.vehicle.getIDList()
        for id in id_list:
            array = get_veh_info(id)

            if len(str(id).split(".")[1]) == 1:
                id = str(id).replace(".", '')
                veh_number = '鲁'+str(id)

            # [lon, lat, angle, speed, vehLength, vehWidth, vehHeight, accel, signal]
                message = '{"id":"' + veh_number + '", "speed": "' + str(array[3]) + \
                      '", "accel": "' + str(array[7]) + '", "lon": "' + str(array[0]) + '", "lat": "' + str(
                    array[1]) + '", "length": "' + str(array[4]) + '", "width": "' + str(
                    array[5]) + '", "height": "' + str(array[6]) + '", "angle": "' + str(
                    array[2]) + '", "signal": "' + str(array[8]) + '", "timestamp": "' + str(
                    int(round((time.time()) * 1000))) + '"}'
                bsm_msg_quene(message)
                warning_quene(message)
                # print(message)
            elif len(str(id).split(".")[1]) == 2:
                id1 = str(id).split(".")[0].replace('0', '', 1)
                id2 = str(id).split(".")[1]
                id = str(id1) + str(id2)
                veh_number = '鲁' + str(id)
                ptcId = function.car_get_ptc_id(veh_number)
                message = '{"id":"' + veh_number + '", "speed": "' + str(array[3]) + \
                          '", "accel": "' + str(array[7]) + '", "lon": "' + str(array[0]) + '", "lat": "' + str(
                    array[1]) + '", "length": "' + str(array[4]) + '", "width": "' + str(
                    array[5]) + '", "height": "' + str(array[6]) + '", "angle": "' + str(
                    array[2]) + '", "signal": "' + str(array[8]) + '", "timestamp": "' + str(
                    int(round((time.time()) * 1000))) + '"}'
                bsm_msg_quene(message)
                warning_quene(message)
                # print(message)

        result = r.rpop("sumo")
        if result is not None:
            # 将json字符串转换为python对象（dict）
            obj = json.loads(result.decode('utf-8'))
            time_interval = obj['timeInterval']
            vehicle_flow = obj['vehicleFlow']
            begin = time_interval.split('-')[0]
            end = time_interval.split('-')[1]

            with open("sumo/road.rou.xml", "r") as f:
                lines = f.readlines()
                lines.insert((len(lines) - 1), '<flow id="FH%s00" from="1046852315" to="1046103598#4" begin="%s" end="%s" number="%s"/>\n' % ((len(lines) - 4), begin, end, vehicle_flow))
                s = ''.join(lines)

            with open("sumo/road.rou.xml", "w") as f:
                f.write(s)
            f.close()


def get_options():
    optParser = optparse.OptionParser()
    optParser.add_option("--nogui", action="store_true",
                         default=False, help="run the commandline version of sumo")
    options, args = optParser.parse_args()
    return options


sumocfgfile = "./sumo/osm.sumocfg"

# this is the main entry point of this script
if __name__ == "__main__":
    options = get_options()
    # this script has been called from the command line. It will start sumo as a
    # server, then connect and run
    if options.nogui:
        sumoBinary = checkBinary('sumo')
    else:
        sumoBinary = checkBinary('sumo-gui')

    # this is the normal way of using traci. sumo is started as a
    # subprocess and then the python script connects and runs
    # generate_routefile()
    traci.start([sumoBinary, "-c", sumocfgfile])
    run()
